<template>
  <div class="page-header-index-wide">
    <a-row :gutter="24">
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="年总销售额"  :total="totalTurnover.sumAll | NumberFormat" >
        
          <a-tooltip title="销售额统计" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <trend flag="up" style="margin-right: 16px;">
              <span slot="term" >月销售额</span>
                 {{ monthTotalTurnover.sumAll| NumberFormat }} 
            </trend>
            <trend flag="up" style="margin-right: 16px;">
              <span slot="term" >日销售额</span>
                 {{ dayTotalTurnover.sumAll| NumberFormat }} 
            </trend>
          </div>
          <template slot="footer">当前日期:  <span>{{time}}</span></template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="年订单量" :total="orderCounts.orderCount | NumberFormat">
          <a-tooltip title="订单量统计" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div >
            <mini-area :data-source="lastTenDaysOrders" x="日期" y="订单量" />
          </div>
          <template slot="footer">月订单量<span> {{ monthOrderCounts.orderCount | NumberFormat }}</span></template>
          <template slot="footer">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</template>
          <template slot="footer">日订单量<span> {{ dayOrderCounts.orderCount | NumberFormat }}</span></template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="年支付笔数" :total="payCount.paysCount | NumberFormat">
          <a-tooltip title="支付笔数统计" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <mini-bar :data-source="lastTenDaysPaysCount"  :height="40" x="日期" y="支付笔数" />
          </div>
          <template slot="footer">月支付<span>{{ monthPayCount.paysCount | NumberFormat }}</span></template>
          <template slot="footer">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</template>
          <template slot="footer">日支付 <span>{{ dayPayCount.paysCount | NumberFormat }}</span></template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="年未结清订单" :total="noSettleOrdersRatio.proportion +'%'| NumberFormat">
          <a-tooltip title="未结清订单统计" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <mini-progress color="rgb(19, 194, 194)" :target="noSettleOrdersRatio.proportion| NumberFormat" :percentage="noSettleOrdersRatio.proportion| NumberFormat" :height="8" />
          </div>
          <template slot="footer">
            <trend flag="down" style="margin-right: 16px;">
              <span slot="term">已结清</span>
              {{ settleOrderCount.orderCount | NumberFormat }}
            </trend>
            <trend flag="up">
              <span slot="term">未结清</span>
              {{ noSettleOrderCount.orderCount | NumberFormat }}
            </trend>
          </template>
        </chart-card>
      </a-col>
    </a-row>

    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <a-tab-pane loading="true" tab="销售额" key="1">
            <a-row > 
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="销售额排行" :dataSource="monthlySales" x="月份" y="销售额"/>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="未结清货款排行榜" :list="lastTopUpaidTotal"/>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane tab="订单量" key="2">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="订单量排行" :dataSource="monthlyOrders" x="月份" y="订单量"/>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="水果销量排行榜" :list="lastTopProductsSales"/>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>

  </div>
</template>

<script>
  import ChartCard from '@/components/ChartCard'
  import ACol from "ant-design-vue/es/grid/Col"
  import ATooltip from "ant-design-vue/es/tooltip/Tooltip"
  import MiniArea from '@/components/chart/MiniArea'
  import MiniBar from '@/components/chart/MiniBar'
  import MiniProgress from '@/components/chart/MiniProgress'
  import RankList from '@/components/chart/RankList'
  import Bar from '@/components/chart/Bar'
  import LineChartMultid from '@/components/chart/LineChartMultid'
  import HeadInfo from '@/components/tools/HeadInfo.vue'

  import Trend from '@/components/Trend'
    
  import {totalTurnover,monthlySales,monthTotalTurnover,dayTotalTurnover,orderCount,
    monthlyOrders,settleOrderCount, noSettleOrderCount,noSettleOrdersRatio,
    monthOrderCount,dayOrderCount,lastTenDaysOrders,payCount,monthPayCount,
    dayPayCount,lastTenDaysPaysCount,lastTopProductsSales,lastTopUpaidTotal} from '@/api/fep/orders'

  const rankList = []
  for (let i = 0; i < 10; i++) {
    rankList.push({
      name: '白鹭岛 ' + (i+1) + ' 号店',
      total: 1234.56 - i * 100
    })
  }

  export default {
    name: "IndexChart",
    components: {
      ATooltip,
      ACol,
      ChartCard,
      MiniArea,
      MiniBar,
      MiniProgress,
      RankList,
      Bar,
      Trend,
      LineChartMultid,
      HeadInfo
    },
    data() {
      return {
        loading: true,
        center: null,
        rankList,
        time: "",
        times: "",
        totalTurnover: {},
        monthlySales: [],
        monthTotalTurnover: {},
        dayTotalTurnover: {},
        orderCounts: {},
        monthlyOrders: [],
        settleOrderCount:{},
        noSettleOrderCount:{},
        noSettleOrdersRatio:{},
        monthOrderCounts: {},
        dayOrderCounts: {},
        lastTenDaysOrders: [],
        payCount: {},
        monthPayCount: {},
        dayPayCount: {},
        lastTenDaysPaysCount: {},
        lastTopProductsSales: [],
        lastTopUpaidTotal: [],
        params_year:{year: new Date().getFullYear().toString()},
        params_month:{month: ""},
        params_day:{day: ""},
        indicator: <a-icon type="loading" style="font-size: 24px" spin />,

      }
    },

    created() {
      
      setTimeout(() => {
        this.loading = !this.loading
      }, 1000)
      this.getCurrentYear();
      this.params_month.month = this.time_month;
      this.params_day.day = this.time_day;
      this.getTotalTurnover();
      this.getMonthlySales();
      this.getMonthTotalTurnover();
      this.getDayTotalTurnover();
      this.getOrderCount();
      this.getMonthlyOrders();
      this.getSettleOrderCount();
      this.getNoSettleOrderCount();
      this.getNoSettleOrdersRatio();
      this.getMonthOrderCount();
      this.getDayOrderCount();
      this.getLastTenDaysOrders();
      this.getpayCount();
      this.getMonthPayCount();
      this.getDayPayCount();
      this.getLastTenDaysPaysCount();
      this.getLastTopProductsSales();
      this.getLastTopUpaidTotal();

    },
    
    methods: {

      // 获取当前年月日
      getCurrentYear() {
        const yy = new Date().getFullYear()
				const MM = (new Date().getMonth() + 1) < 10 ? '0' + (new             
                    Date().getMonth() + 1) : (new Date().getMonth() + 1)
				const dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new 
                    Date().getDate()
				const HH = new Date().getHours() < 10 ? '0' + new Date().getHours() : new 
                    Date().getHours()
				const mm = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : 
                     new Date().getMinutes()
				const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : 
                     new Date().getSeconds()
        this.time_month = yy + '-' + MM;
				this.time_day = yy + '-' + MM + '-' + dd ;
        this.time= yy + '-' + MM + '-' + dd + "     " + HH+ ':' + mm+ ':' + ss;
          },

      // 获取年销售额
      getTotalTurnover(){
        this.loading = true;
        totalTurnover(this.params_year).then(res=>{
          if(res.success){
            this.totalTurnover=res.result;
          }else{
            this.totalTurnover=0;
          }
        })
      },

      // 获取年度销售额
      getMonthlySales(){
        this.loading = true;
        monthlySales(this.params_year).then(response=>{
        // 获取result中的数据
        const monthlySalesResults =response.result;
        // 对结果进行排序，按照 orderTime 排序
        const sortedResults  = monthlySalesResults.sort((a, b) => new Date(a.orderTime) - new Date(b.orderTime));
        //获取 x（支付时间） 和 y（销售额） 的值
        const monthlySalesXy=  sortedResults.map(orders => {
          let month = parseInt(orders.orderTime.substring(5, 7), 10).toString();
          return {
                x: `${month}月`, 
                y: parseFloat(orders.sumAll)};  
      });
        this.monthlySales =monthlySalesXy;
           //console.table("monthlySales--------"+this.monthlySales)
        }).catch(error => {
           console.error("Error fetching monthlySales:", error);
           this.monthlySales = [];
      });
      },
    
      // 获取月销售额
      getMonthTotalTurnover(){
        this.loading = true;
        monthTotalTurnover(this.params_month).then(res=>{
          if(res.success){
            this.monthTotalTurnover=res.result;
          }else{
          
            this.monthTotalTurnover=0;
          }
        })
      },
      // 获取日销售额
      getDayTotalTurnover(){
        this.loading = true;
        dayTotalTurnover(this.params_day).then(res=>{
          if(res.success){
            this.dayTotalTurnover=res.result;
          }else{
          
            this.dayTotalTurnover=0;
          }
        })
      },
       // 获取年订单数
      getOrderCount(){
        this.loading = true;
        orderCount(this.params_year).then(res=>{
          if(res.success){
            this.orderCounts=res.result;
          }else{
            this.orderCounts=0;
          }
        })
      },


      // 获取年度订单量
      getMonthlyOrders(){
        this.loading = true;
        monthlyOrders(this.params_year).then(response=>{
        // 获取result中的数据
        const monthlyOrdersResults =response.result;
        // 对结果进行排序，按照 orderTime 排序
        const sortedResults = monthlyOrdersResults.sort((a, b) => new Date(a.orderTime) - new Date(b.orderTime));
        //获取 x（支付时间） 和 y（销售额） 的值
        const monthlyOrdersXy=  sortedResults.map(orders => {
          let month = parseInt(orders.orderTime.substring(5, 7), 10).toString();
          return {
            x: `${month}月`, 
            y: parseInt(orders.orderCount)};  
      });
        this.monthlyOrders =monthlyOrdersXy;
       //console.table("monthlyOrders--------"+this.monthlyOrders)
        }).catch(error => {
       console.error("Error fetching monthlyOrders:", error);
       this.monthlyOrders = [];
      });
      },

      // 获取年已结清订单数
      getSettleOrderCount(){
        this.loading = true;
        settleOrderCount(this.params_year).then(res=>{
          if(res.success){
            this.settleOrderCount=res.result;
          }else{
            this.settleOrderCount=0;
          }
        })
      },
       // 获取年未结清订单数
       getNoSettleOrderCount(){
        this.loading = true;
        noSettleOrderCount(this.params_year).then(res=>{
          if(res.success){
            this.noSettleOrderCount=res.result;
          }else{
            this.noSettleOrderCount=0;
          }
        })
      },     
       // 获取年未结清订单占比
       getNoSettleOrdersRatio(){
        this.loading = true;
        noSettleOrdersRatio(this.params_year).then(res=>{
          if(res.success){
            this.noSettleOrdersRatio=res.result;
          }else{
            this.noSettleOrdersRatio=0;
          }
        })
      },    
      // 获取月订单数
      getMonthOrderCount(){
        this.loading = true;
        monthOrderCount(this.params_month).then(res=>{
          if(res.success){
            this.monthOrderCounts=res.result;
          }else{
            this.monthOrderCounts=0;
          }
        })
      },
      // 获取日订单数
      getDayOrderCount(){
        this.loading = true;
        dayOrderCount(this.params_day).then(res=>{
          if(res.success){
            this.dayOrderCounts=res.result;
          }else{
            this.dayOrderCounts=0;
          }
        })
      },

      // 获取十日订单数
      getLastTenDaysOrders() {
       this.loading = true;
       lastTenDaysOrders(this.params_day).then(response => {
        // 获取result中的数据
        const lastTenDayOrdersResult = response.result;
        // 对结果进行排序，按照 orderTime 排序
        const sortedResults = lastTenDayOrdersResult.sort((a, b) => new Date(a.orderTime) - new Date(b.orderTime));
       // 获取 x（支付时间） 和 y（订单数） 的值
       const lastTenDaysOrdersXy = sortedResults.map(orders => {
           return {
             x: orders.orderTime,
             y: parseInt(orders.orderCount)
         };
        });
       this.lastTenDaysOrders =lastTenDaysOrdersXy;
        //console.table(“lastTenDaysOrders----”+this.lastTenDaysOrders);
       }).catch(error => {
       console.error("Error fetching last ten days orders:", error);
       this.lastTenDaysOrders = [];
      });
      },


      // 获取年支付笔数
      getpayCount(){
        this.loading = true;
        payCount(this.params_year).then(res=>{
          if(res.success){
            this.payCount=res.result;
          }else{
            this.payCount=0;
          }
        })
      }, 
       // 获取月支付笔数
      getMonthPayCount(){
        this.loading = true;
        monthPayCount(this.params_month).then(res=>{
          if(res.success){
            this.monthPayCount=res.result;
          }else{
            this.monthPayCount=0;
          }
        })
      },  
       // 获取日支付笔数
      getDayPayCount(){
        this.loading = true;
        dayPayCount(this.params_day).then(res=>{
          if(res.success){
            this.dayPayCount=res.result;
          }else{
            this.dayPayCount=0;
          }
        })
      },   
      
      // 获取十日支付笔数
      getLastTenDaysPaysCount() {
       this.loading = true;
       lastTenDaysPaysCount(this.params_day).then(response => {
        // 获取result中的数据
        const lastTenDaysPaysResult = response.result;
       // 将数据按照 payTime 排序
        const sortedResults = lastTenDaysPaysResult.sort((a, b) => new Date(a.payTime) - new Date(b.payTime));
       // 获取 x（支付时间） 和 y（支付笔数） 的值
        const lastTenDaysPaysCountXY = sortedResults.map(pays => {
           return {
             x: pays.payTime,
             y: parseInt(pays.paysCount)
         };
        });
       this.lastTenDaysPaysCount =lastTenDaysPaysCountXY;
     //  console.table("lastTenDaysPaysCount---"+this.lastTenDaysPaysCount);
       }).catch(error => {
       console.error("Error fetching last ten days pay:", error);
       this.lastTenDaysPaysCount = [];
      });
      },

     // 获取销量top10的水果
     getLastTopProductsSales() {
       this.loading = true;
       lastTopProductsSales(this.params_year).then(response => {
        // 获取result中的数据
        const lastTopProductsSalesResult = response.result;
       // 将数据按照 totalQuantity 排序
        const sortedResults = lastTopProductsSalesResult.sort((a, b) => b.totalQuantity - a.totalQuantity);
       // 获取 x（支付时间） 和 y（支付笔数） 的值
        const lastTopProductsSalesXY = sortedResults.map(item => {
           return {
             name: item.productName,
             total: parseInt(item.totalQuantity)
         };
        });
       this.lastTopProductsSales =lastTopProductsSalesXY;
     //  console.table("lastTopProductsSales---"+this.lastTopProductsSales);
       }).catch(error => {
       console.error("Error fetching last ten days pay:", error);
       this.lastTopProductsSales = [];
      });
      },


     // 获取欠费top10
     getLastTopUpaidTotal() {
       this.loading = true;
       lastTopUpaidTotal().then(response => {
        // 获取result中的数据
        const lastTopUpaidTotalResult = response.result;
       // 将数据按照 totalQuantity 排序
        const sortedResults = lastTopUpaidTotalResult.sort((a, b) => b.totalUpaid - a.totalUpaid);
       // 获取 x（支付时间） 和 y（支付笔数） 的值
        const lastTopUpaidTotalXY = sortedResults.map(item => {
           return {
             name: item.username,
             total: parseFloat(item.totalUpaid)
         };
        });
       this.lastTopUpaidTotal =lastTopUpaidTotalXY;
     //  console.table("lastTopUpaidTotal---"+this.lastTopUpaidTotal);
       }).catch(error => {
       console.error("Error fetching last ten days pay:", error);
       this.lastTopUpaidTotal = [];
      });
      },




  
    }
  }
</script>

<style lang="less" scoped>
  .circle-cust{
    position: relative;
    top: 28px;
    left: -100%;
  }
  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }

</style>